package cn.jekun.shop.common.service;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.JsonObject;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.D;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.RsBank;
import cn.jekun.component.core.bean.gen.RsSms;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.SgAccount;
import cn.jekun.component.core.bean.gen.SgSettleApply;
import cn.jekun.component.core.bean.gen.TsAccount;
import cn.jekun.component.core.service.SMSService;
import cn.jekun.component.core.service.SettleApplyService;
import cn.jekun.component.core.service.gen.ErpShopService;
import cn.jekun.component.core.service.gen.RsBankService;
import cn.jekun.component.core.service.gen.RsSmsService;
import cn.jekun.component.core.service.gen.SgAccountService;
import cn.jekun.component.core.validator.annotation.Identity;
import cn.jekun.shop.web.bean.BanksAccount;
import cn.jekun.shop.web.bean.SgAccounts;
import cn.jekun.shop.web.bean.ShopBusiness;

/**
 * 银行账户管理Service
 *
 */
@Service(BanksService.BEAN_NAME)
public class BanksService extends ShopBaseService{
	public static final String BEAN_NAME="cn.jekun.shop.web.service.BanksAccountService";
	@Resource(name=SettleApplyService.BEAN_NAME)
	protected SettleApplyService settleApplyService;
	@Resource(name=SgAccountService.BEAN_NAME)
	protected SgAccountService sgAccountService;
	@Resource(name = RsSmsService.BEAN_NAME)
	RsSmsService rsSmsService;
	@Resource(name = ErpShopService.BEAN_NAME)
	ErpShopService erpShopService;
	
	@Resource(name=RsBankService.BEAN_NAME)
	RsBankService rsBankService;
	
	@Override
	public String getNamespace() {
		// TODO Auto-generated method stub
		return "ACTION_TS_BANKS_ACCOUNTS";
	}

	/**
	 * 获取商户所有绑定的结算账户
	 * @param map
	 * @return
	 */
	public JSONObject getBanksAccounts( @RsUser.AnnoUserId String userId,String pageSize,
			@Security
			String currentPage){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		if (StringUtils.isNotBlank(pageSize)) {
			page.setPageSize(Integer.parseInt(pageSize));
		}
		if (StringUtils.isNotBlank(currentPage)) {
			page.setPageNumber(Integer.parseInt(currentPage));
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		Map map=new HashMap<String, String>();
		map.put("userId", userId);
		JSONArray jsonArray = JSONArray.fromObject(this.list(this.getStatementName("list"),map,page));
		jsonObject.put("BankListData", jsonArray);
		jsonObject.put("totals", page.getTotalCount());
		jsonObject.put("pages", page.getPages());
		jsonObject.put("pageSize", page.getPageSize());
		jsonObject.put("currentPage", page.getPageNumber());
		
		return executeRerutn(jsonObject);

	}


	/**
	 * 获取提现的银行账户信息
	 * @return
	 */
	public BanksAccount getBankAccount(String userId){
		Map formMap = null;
    	formMap = new HashMap();
        formMap.put("userId",userId);
		return this.one(this.getStatementName("queryWithdrawBankAccount"),formMap);
	}

//	/**
//	 * 
//	 * @param userId 用户代码
//	 * @param accountId 提现账户代码
//	 * @param amount 提现金额
//	 * @param amount 提现费用
//	 * @param paypwd 支付密码
//	 * @return 提现申请流水代码
//	 */
//	@Transactional
//	public String settleApply(@RsUser.AnnoUserId String userId,@SgSettleApply.AnnoAccountId String accountId,@SgSettleApply.AnnoAmount double amount,@SgSettleApply.AnnoFee double fee,@TsAccount.AnnoPassword String paypwd){
//		
//		//记录账户流水，增加提现申请
//		String settleApplyId = null;//提现申请代码
//		try {
//			settleApplyId = this.settleApplyService.settleApply(userId,accountId,paypwd,amount,fee,Constants.SG_APPLY_TYPE.SHOP_WEB);//事务 //TODO 通过网站后台提现的，没有流水代码?
//		} catch (Exception e) {
//			e.printStackTrace();
//			if (e instanceof BusinessException) {
//				throw (BusinessException) e;
//			} else {
//				throw new BusinessException(Constants.ERRORS.WITHDRAW_ERROR,"申请提现失败" + e.getMessage());
//			}
//		}
//		return settleApplyId;
//	}
	
	public JSONObject listSettleApply(@RsUser.AnnoUserId String userId,@D String beginDate,@D String endDate,@Num(length=10,scale=3) String beginMoney,@Num(length=10,scale=3) String endMoney,@Security String bankName,@Security
			String pageSize,
			@Security
			String currentPage){
		
//		Map formMap=new HashMap<String, String>();
//		formMap.put("beginDate", beginDate);
//		formMap.put("endDate", endDate);
//		
//		formMap.put("shopId", shopId);
//		SqlUtis.convertBetweenValue(formMap, "commitTime");
//		SqlUtis.prepareSql(formMap
//				,SqlUtis.getSQL(formMap, "a."+SgSettleApply.COL_COMMIT_TIME,"commitTime", Types.DATE)
//				,SqlUtis.getSQL(formMap, "u."+RsUser.COL_REAL_NAME, realName, Types.VARCHAR,SqlUtis.LIKE)
//				,SqlUtis.getSQL(formMap, "u."+RsUser.COL_USER_NAME, userName, Types.VARCHAR,SqlUtis.LIKE)
//				);\
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		if (StringUtils.isNotBlank(pageSize)) {
			page.setPageSize(Integer.parseInt(pageSize));
		}
		if (StringUtils.isNotBlank(currentPage)) {
			page.setPageNumber(Integer.parseInt(currentPage));
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		
		String SQL = "";
		if("".equals(beginDate) && !"".equals(endDate)){
			SQL +=" and a.create_time"
					+ "<= to_date('"+beginDate.toString().trim()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginDate) && "".equals(endDate)){
			SQL +=" and a.create_time"
					+ ">= to_date('"+beginDate.toString().trim()+"','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginDate) && beginDate!=null 
				&& !"".equals(endDate) && endDate!=null){
			SQL +=" and a.create_time >= to_date('"+beginDate.toString().trim()+"','yyyy/MM/dd hh24:mi:ss')"
					+ " and a.create_time <= to_date('"+endDate.toString().trim()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginMoney) && "".equals(endMoney)){
			SQL +=" and a.amount>="+beginMoney; 
		}if("".equals(beginMoney) && !"".equals(endMoney)){
			SQL +=" and a.amount<="+endMoney; 
		}if(beginMoney!=null && endMoney!=null && !"".equals(beginMoney) 
				&& !"".equals(endMoney)){
			SQL +=" and a.amount>="+beginMoney+" and a.amount<="+endMoney+""; 
		}
		if(bankName!=null && bankName.toString().length()>0){
			SQL +=" and e.BANK_NAME like '%"+bankName.toString()+"%'"; 
		}
		
	    System.out.println("SQL="+SQL);
		Map map=new HashMap();
		map.put("userId", userId);
		SqlUtis.prepareSql(map,SQL);
		
//		return this.list(this.getStatementName("listSettleApply"), formMap,page);
		JSONArray jsonArray = JSONArray.fromObject(this.list(this.getStatementName("listSettleApply"), map,page));
		jsonObject.put("settleListData", jsonArray);
		jsonObject.put("totals", page.getTotalCount());
		jsonObject.put("pages", page.getPages());
		jsonObject.put("pageSize", page.getPageSize());
		jsonObject.put("currentPage", page.getPageNumber());
		return executeRerutn(jsonObject);
	}

	/**
	 * 获取银行列表
	 * @return
	 */
	public List<BanksAccount> getBanks(@RsBank.AnnoBankId String bankId,@RsBank.AnnoBankName String bankName,Page page){
		Map formMap=new HashMap();
		
		String SQL = "";
		
		if(bankId!=null && bankId.toString().length()>0){
			SQL +=" and a.bank_id like '%"+bankId.toString()+"%'"; 
		}
		if(bankName!=null && bankName.toString().length()>0){
			SQL +=" and a.bank_name like '%"+bankName.toString()+"%'"; 
		}
		
	    System.out.println("SQL="+SQL);
		Map map=new HashMap();
		SqlUtis.prepareSql(formMap,SQL);
		
		
		return this.list(this.getStatementName("queryBanks"),formMap,page);
	}

	/**
	 * 获取证件种类列表
	 * @return
	 */
	public List<BanksAccount> getIdCards(){
		return this.list(this.getStatementName("queryidCards"),null);
	}

	/**
	 * 设定为默认结算账户
	 * @param shopId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public boolean setDefaultAccounts(@RsUser.AnnoUserId String userId,@SgAccount.AnnoAccountId String accountId){
		try {
			//更新当前商户的其它账户为非默认
			SgAccount updateSgAccount = new SgAccount();
			updateSgAccount.setDefaultFlag("0");
			updateSgAccount.setOwnerId(userId);
			Map updateMap=new HashMap();
			updateMap.put("sgAccount", updateSgAccount);
			updateMap.put(SgAccount.COL_OWNER_ID, updateSgAccount.getOwnerId());
			SqlUtis.prepareSql(updateMap, "",
					SqlUtis.getSQLRequired(updateMap, "a."+updateSgAccount.COL_OWNER_ID, Types.VARCHAR));
			this.sgAccountService.update(updateMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			SgAccount updateCurrSgAccount = new SgAccount();
			Map map = new HashMap();
			updateCurrSgAccount.setDefaultFlag("1");
			updateCurrSgAccount.setOwnerId(userId);
			updateCurrSgAccount.setAccountId(accountId);
			map.put("sgAccount",updateCurrSgAccount);
			map.put(SgAccount.COL_OWNER_ID, updateCurrSgAccount.getOwnerId());
			map.put(SgAccount.COL_ACCOUNT_ID, updateCurrSgAccount.getAccountId());
			SqlUtis.prepareSql(map, "",
					SqlUtis.getSQLRequired(map, "a."+updateCurrSgAccount.COL_ACCOUNT_ID, Types.VARCHAR),
					SqlUtis.getSQLRequired(map, "a."+updateCurrSgAccount.COL_OWNER_ID, Types.VARCHAR));
			this.sgAccountService.update(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

//	/**
//	 * 绑定银行账户
//	 * @return
//	 */
//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	@Transactional
//	public JSONObject getBindBankCard(@SgAccount.AnnoAccountName String accountName,
//								   @SgAccount.AnnoBankId String bankId,
//								   @SgAccount.AnnoBankNumber String bankNumber,
//								   @SgAccount.AnnoMobile String mobile,
//								   String validateCode,
//								   @SgAccount.AnnoDefaultFlag String defaultaccount,
//								   @RsUser.AnnoUserId String userId,
//								   @SgAccount.AnnoIdentifyTypeId String identifyTypeId,
//								   @Identity @SgAccount.AnnoIdentity String identity,
//								   @SgAccount.AnnoAccountType String accountType,
//								   String ownerTypeId){
//		Map map = new HashMap();
//		JSONObject jsonObject=new JSONObject();
//		try {
//			if(!validateCode.equals("NO")){
//				if(ownerTypeId.equals(Constants.TS_ACCOUNT_OWNER_TYPE.USER)){
//					RsUser rsUser = rsUserService.one(userId);
//					// 短信验证码验证（查找最新的短信信息验证码）
//					String tempCode = null;// 手机验证码
//					Map tempSmsMap = new HashMap();
//					tempSmsMap.put(RsSms.COL_MOBILE, rsUser.getMobile());
//					tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.BIND_BANK_CODE);
//					SqlUtis.prepareSql(tempSmsMap, "and round(to_number(sysdate - a.create_time) * 1440) < 30", 
//							SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
//							SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
//							.orderBy(" a.create_time desc"));
//					Page smsPage = new Page();
//					smsPage.setPageSize(1);
//					List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
//					if (smsList != null && smsList.size() >= 1) {
//						RsSms rsSms = smsList.get(0);
//						tempCode = rsSms.getMemo();
//					}
//					if (!validateCode.equals(tempCode)) {
//						jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//
//						jsonObject.put(ErrorMsg.KEY_MESSAGE,"验证码不对！");
//						return jsonObject;
//					}
//					
//				}else if(ownerTypeId.equals(Constants.TS_ACCOUNT_OWNER_TYPE.SHOP)){
//					ErpShop erpShop = erpShopService.one(userId);
//					// 短信验证码验证（查找最新的短信信息验证码）
//					String tempCode = null;// 手机验证码
//					Map tempSmsMap = new HashMap();
//					tempSmsMap.put(RsSms.COL_MOBILE, erpShop.getMobile());
//					tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.BIND_BANK_CODE);
//					SqlUtis.prepareSql(tempSmsMap, "and round(to_number(sysdate - a.create_time) * 1440) < 30", 
//							SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
//							SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
//							.orderBy(" a.create_time desc"));
//					Page smsPage = new Page();
//					smsPage.setPageSize(1);
//					List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
//					if (smsList != null && smsList.size() >= 1) {
//						RsSms rsSms = smsList.get(0);
//						tempCode = rsSms.getMemo();
//					}
//					if (!validateCode.equals(tempCode)) {
//						jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//
//						jsonObject.put(ErrorMsg.KEY_MESSAGE,"验证码不对！");
//						return jsonObject;
//					}
//				}
//			}
//			
//			SgAccounts sgAccounts = new SgAccounts();
//			sgAccounts.setOwnerTypeId(ownerTypeId);//户主类型
//			sgAccounts.setOwnerId(userId); //户主代码
//			sgAccounts.setAccountTypeId(Constants.TS_ACCOUNT_TYPE.SETTLE); //账户类型
//			sgAccounts.setAccountName(accountName);
//			sgAccounts.setBankId(bankId);
//			sgAccounts.setBankNumber(bankNumber);
//			sgAccounts.setIdentifyTypeId(identifyTypeId);
//			sgAccounts.setIdentity(identity);
//			sgAccounts.setBankNumber(bankNumber);
//			sgAccounts.setMobile(mobile);
//			sgAccounts.setAccountType(accountType);
//			if(defaultaccount!=null && "1".equals(defaultaccount)){
//				//更新当前商户的其它账户为非默认
//				SgAccount updateSgAccount = new SgAccount();
//				updateSgAccount.setDefaultFlag("0");
//				sgAccounts.setDefaultFlag("1"); //是否默认为结算账户(提现标志) 1-是/0-否
//				updateSgAccount.setOwnerId(userId);
//				Map updateMap=new HashMap();
//				updateMap.put("sgAccount", updateSgAccount);
//				updateMap.put(SgAccount.COL_OWNER_ID, updateSgAccount.getOwnerId());
//				SqlUtis.prepareSql(updateMap, "",
//						SqlUtis.getSQLRequired(updateMap, "a."+updateSgAccount.COL_OWNER_ID, Types.VARCHAR));
//				this.sgAccountService.update(updateMap);		
//			}else{
//				sgAccounts.setDefaultFlag("0"); //是否默认为结算账户(提现标志) 1-是/0-否	
//			}
//			sgAccounts.setAvailable("1"); //有效标志  1-有效/0-无效、解绑
//			map.put("sgAccounts", sgAccounts);
//			String accountId = (String)this.insert(map);
//			
//			RsBank  rsBank = rsBankService.one(bankId);
//			jsonObject.put("bankId", bankId);
//			jsonObject.put("bankName", rsBank.getBankName());
//			jsonObject.put("accountName", accountName);
//			jsonObject.put("bankNumber", bankNumber);
//			jsonObject.put("accountId", accountId);
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
//
//		jsonObject.put(ErrorMsg.KEY_MESSAGE,"绑定银行卡成功，银行卡号:"+bankNumber);
//		return jsonObject;
//	}
	
	
	/**
	 * 绑定银行账户(无判断身份证是否合法)
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public JSONObject getBindBankCardNoIden(@SgAccount.AnnoAccountName String accountName,
								   @SgAccount.AnnoBankId String bankId,
								   @SgAccount.AnnoBankNumber String bankNumber,
								   @SgAccount.AnnoMobile String mobile,
								   String validateCode,
								   @SgAccount.AnnoDefaultFlag String defaultaccount,
								   @RsUser.AnnoUserId String userId,
								   @SgAccount.AnnoIdentifyTypeId String identifyTypeId,
								   String identity,
								   @SgAccount.AnnoAccountType String accountType,
								   String ownerTypeId){
		Map map = new HashMap();
		JSONObject jsonObject=new JSONObject();
		try {
//			if(!validateCode.equals("NO")){
//				if(ownerTypeId.equals(Constants.TS_ACCOUNT_OWNER_TYPE.USER)){
					RsUser rsUser = rsUserService.one(userId);
					// 短信验证码验证（查找最新的短信信息验证码）
					String tempCode = null;// 手机验证码
					Map tempSmsMap = new HashMap();
					tempSmsMap.put(RsSms.COL_MOBILE, rsUser.getMobile());
					tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.BIND_BANK_CODE);
					SqlUtis.prepareSql(tempSmsMap, "and round(to_number(sysdate - a.create_time) * 1440) < 30", 
							SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
							SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
							.orderBy(" a.create_time desc nulls last"));
					Page smsPage = new Page();
					smsPage.setPageSize(1);
					List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
					if (smsList != null && smsList.size() >= 1) {
						RsSms rsSms = smsList.get(0);
						tempCode = rsSms.getMemo();
					}
					if (!validateCode.equals(tempCode)) {
						jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);

						jsonObject.put(ErrorMsg.KEY_MESSAGE,"验证码不对！");
						return jsonObject;
					}
					
//				}else if(ownerTypeId.equals(Constants.TS_ACCOUNT_OWNER_TYPE.SHOP)){
//					ErpShop erpShop = erpShopService.one(userId);
//					// 短信验证码验证（查找最新的短信信息验证码）
//					String tempCode = null;// 手机验证码
//					Map tempSmsMap = new HashMap();
//					tempSmsMap.put(RsSms.COL_MOBILE, erpShop.getMobile());
//					tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.BIND_BANK_CODE);
//					SqlUtis.prepareSql(tempSmsMap, "and round(to_number(sysdate - a.create_time) * 1440) < 30", 
//							SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
//							SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
//							.orderBy(" a.create_time desc"));
//					Page smsPage = new Page();
//					smsPage.setPageSize(1);
//					List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
//					if (smsList != null && smsList.size() >= 1) {
//						RsSms rsSms = smsList.get(0);
//						tempCode = rsSms.getMemo();
//					}
//					if (!validateCode.equals(tempCode)) {
//						jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//
//						jsonObject.put(ErrorMsg.KEY_MESSAGE,"验证码不对！");
//						return jsonObject;
////						throw new BusinessException("-3210",
////								"验证码不对！");
//					}
//				}
//			}
			
			
			SgAccounts sgAccounts = new SgAccounts();
			sgAccounts.setOwnerTypeId(ownerTypeId);//户主类型
			sgAccounts.setOwnerId(userId); //户主代码
			sgAccounts.setAccountTypeId(Constants.TS_ACCOUNT_TYPE.SETTLE); //账户类型
			sgAccounts.setAccountName(accountName);
			sgAccounts.setBankId(bankId);
			sgAccounts.setBankNumber(bankNumber);
			sgAccounts.setIdentifyTypeId(identifyTypeId);
			sgAccounts.setIdentity(identity);
			sgAccounts.setBankNumber(bankNumber);
			sgAccounts.setMobile(mobile);
			sgAccounts.setAccountType(accountType);
			
			//是否存在默认的银行卡
			Map existsMap=new HashMap();
			existsMap.put(SgAccount.COL_OWNER_ID, sgAccounts.getOwnerId());
			existsMap.put(SgAccount.COL_OWNER_TYPE_ID, sgAccounts.getOwnerTypeId());
			existsMap.put(SgAccount.COL_DEFAULT_FLAG, "1");
			SqlUtis.prepareSql(existsMap, "",
					SqlUtis.getSQLRequired(existsMap, "a."+SgAccount.COL_OWNER_ID, Types.VARCHAR)
					,SqlUtis.getSQLRequired(existsMap, "a."+SgAccount.COL_OWNER_TYPE_ID, Types.VARCHAR)
					,SqlUtis.getSQLRequired(existsMap, "a."+SgAccount.COL_DEFAULT_FLAG, Types.VARCHAR)
					);
			if(!sgAccountService.exists(existsMap)){
				sgAccounts.setDefaultFlag("1"); //是否默认为结算账户(提现标志) 1-是/0-否
			}else{
				if(defaultaccount!=null && "1".equals(defaultaccount)){
					//更新当前商户的其它账户为非默认
					SgAccount updateSgAccount = new SgAccount();
					updateSgAccount.setDefaultFlag("0");
					sgAccounts.setDefaultFlag("1"); //是否默认为结算账户(提现标志) 1-是/0-否
					updateSgAccount.setOwnerId(userId);
					Map updateMap=new HashMap();
					updateMap.put("sgAccount", updateSgAccount);
					updateMap.put(SgAccount.COL_OWNER_ID, updateSgAccount.getOwnerId());
					updateMap.put(SgAccount.COL_OWNER_TYPE_ID, ownerTypeId);
					SqlUtis.prepareSql(updateMap, "",
							SqlUtis.getSQLRequired(updateMap, "a."+SgAccount.COL_OWNER_ID, Types.VARCHAR)
							,SqlUtis.getSQLRequired(updateMap, "a."+SgAccount.COL_OWNER_TYPE_ID, Types.VARCHAR));
					this.sgAccountService.update(updateMap);		
				}else{
					sgAccounts.setDefaultFlag("0"); //是否默认为结算账户(提现标志) 1-是/0-否	
				}
			}
			sgAccounts.setAvailable("1"); //有效标志  1-有效/0-无效、解绑
			map.put("sgAccounts", sgAccounts);
			String accountId = (String)this.insert(map);
			
			RsBank  rsBank = rsBankService.one(bankId);
			jsonObject.put("bankId", bankId);
			jsonObject.put("bankName", rsBank.getBankName());
			jsonObject.put("accountName", accountName);
			jsonObject.put("bankNumber", bankNumber);
			jsonObject.put("accountId", accountId);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

		jsonObject.put(ErrorMsg.KEY_MESSAGE,"绑定银行卡成功，银行卡号:"+bankNumber);

		return jsonObject;
	}
	
	
	/**
	 * 解除绑定
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public boolean updateSgAccount(@SgAccount.AnnoDefaultFlag String defaultFlag,
							   	   @SgAccount.AnnoAvailable String available,
							   	   @NotBlank @SgAccount.AnnoAccountId String accountId){
		Map map = new HashMap();
		SgAccount sgAccount=new SgAccount();
		if(defaultFlag!=null){
			sgAccount.setDefaultFlag(defaultFlag); //是否默认为结算账户(提现标志) 1-是/0-否
		}
		if(available!=null){
			sgAccount.setAvailable(available); //有效标志  1-有效/0-无效、解绑
		}
		map.put("sgAccount", sgAccount);
		map.put(SgAccount.COL_ACCOUNT_ID, accountId);
		SqlUtis.prepareSql(map, "",
				SqlUtis.getSQLRequired(map, "a."+SgAccount.COL_ACCOUNT_ID, Types.VARCHAR));
		this.sgAccountService.update(map);

		return true;
	}
	
	
	

//	/**
//	 * 判断是否有相同卡号
//	 * @return
//	 */
//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	public boolean isBanksNumber(@SgAccount.AnnoBankNumber String bankNumber){
//		SgAccount querysg = new SgAccount();
//		Map isnumbermap = new HashMap();
//		querysg.setBankNumber(bankNumber);
//		isnumbermap.put(querysg.COL_BANK_NUMBER, querysg.getBankNumber()); //where条件值,put->Map
//		isnumbermap.put("sgAccount", querysg);
//		SqlUtis.prepareSql(isnumbermap,
//				SqlUtis.getSQL(isnumbermap, "a."+querysg.COL_BANK_NUMBER, Types.VARCHAR));
//		return this.sgAccountService.count(isnumbermap)>0?true:false;
//	}
	
	/**
	 * 判断当前账户是否是唯一结算账户
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean isDefaultAccount(@SgAccount.AnnoAccountId String accountId){
	  SgAccount sgAccount = new SgAccount();
	  Map accountmap = new HashMap();
	  sgAccount.setDefaultFlag("1");
	  sgAccount.setAccountId(accountId);
	  accountmap.put(sgAccount.COL_DEFAULT_FLAG, sgAccount.getDefaultFlag()); ////where条件值,put->Map
	  accountmap.put(sgAccount.COL_ACCOUNT_ID, sgAccount.getAccountId()); 
	  accountmap.put("sgAccount", sgAccount); //单表操作,map-key值需与对应的配置ibatis-xml配置文件匹配
	  SqlUtis.prepareSql(accountmap, SqlUtis.getSQL(accountmap, "a."+sgAccount.COL_DEFAULT_FLAG,Types.VARCHAR)
			  , SqlUtis.getSQL(accountmap, "a."+sgAccount.COL_ACCOUNT_ID,Types.VARCHAR));
	  return this.sgAccountService.count(accountmap)==1?true:false;	  
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject getBindBankValidateCode(
			String ownerId,
			String ownerTypeId){
		Map formMap = new HashMap();
		JSONObject jsonObject = new JSONObject();
		/*if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机不能为空");
		}*/
		String mobile = "";
		if(ownerTypeId.equals(Constants.TS_ACCOUNT_OWNER_TYPE.USER)){
			RsUser rsUser = rsUserService.one(ownerId);
			if(rsUser != null){
				mobile = rsUser.getMobile();
			}else{
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"此用户不存在");
			}
		}else if(ownerTypeId.equals(Constants.TS_ACCOUNT_OWNER_TYPE.SHOP)){
			ErpShop erpShop = erpShopService.one(ownerId);
			if(erpShop != null){
				mobile = erpShop.getMobile();
			}else{
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"此商家不存在");
			}
		}
		
		formMap.put(RsUser.COL_MOBILE, mobile);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ));
//		boolean flag = rsUserService.exists(formMap);
		
//		if (!flag) {
//			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
//					"此用户不存在");
//		}else{
			SMSService.checkTime(mobile);//检查发送间隔
			//一小时最多三条
			if(!this.smsService.checkOverTimes(mobile, Constants.RS_SMS_TYPE.BIND_BANK_CODE, "1", 3)){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"一小时最多3条,请稍后再操作");
			}
			//一天最多5条
			if(!this.smsService.checkOverTimes(mobile, 	Constants.RS_SMS_TYPE.BIND_BANK_CODE, "24", 5)){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"一天最多5条,请稍后再操作");
			}
			//发送忘记密码的手机验证码
			try {
				// 生成随机类
				Random random = new Random();
				// 取随机产生的认证码(4位数字)
				String sRand = "";
				for (int i = 0; i < 6; i++) {
					String rand = String.valueOf(random.nextInt(10));
					sRand += rand;
				}
				String content = "您正在绑定银行卡，验证码"+sRand+"，请在页面填写，如非本人操作，请忽略。" ;
//				// 将认证码存入数据库
//				Map insertMap = new HashMap();
//				RsSms rsSms = new RsSms();
//				rsSms.setContent(content);
//				rsSms.setMemo(sRand);
//				rsSms.setMobile(mobile);
//				rsSms.setSmsTypeId(Constants.RS_SMS_TYPE.BIND_BANK_CODE);// 绑定银行卡验证码
//				insertMap.put("rsSms", rsSms);
//				rsSmsService.insert(insertMap);
				// 发送短信
				String error = this.smsService.sendSMS(mobile, content, Constants.RS_SMS_TYPE.BIND_BANK_CODE, sRand);
				if (error != null) {
					jsonObject.put(ErrorMsg.KEY_MESSAGE, error);
					return this.executeRerutnFail(jsonObject);
				}
				return this.executeRerutn(jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
				return this.executeRerutnFail(jsonObject);
			}
	}
	
	/**
	 *  刪除银行卡
	 *  @param deviceId
	 *  @return
	 *
	 */
	@Transactional
	public JSONObject deleteBank(String accountId){
		
		JSONObject jsonObject = new JSONObject();
		
		if(StringUtils.isBlank(accountId)){
			throw new BusinessException(ErrorMsg.KEY_MESSAGE,"银行卡代码不能为空");
		}
		
		try{
			Map map=new HashMap();
			map.put(SgAccount.COL_ACCOUNT_ID, accountId);
			SqlUtis.prepareSql(map, SqlUtis.getSQL(map, SgAccount.COL_ACCOUNT_ID,Types.VARCHAR,SqlUtis.EQ));
			
			this.sgAccountService.delete(accountId);
		
		}catch(Exception e){
			return this.executeRerutnFail(jsonObject);
		}
		return this.executeRerutn(jsonObject);
	}

}
